<?php

namespace App\Service\Common;

use App\Models\Common\ShortUrlMappingModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ShortUrlService
{
    //1. 添加
    //2. 查询
    public static function addUrl($url, $code = '')
    {
        //先查表     是否已经存在数据
        $shortUrlModel = ShortUrlMappingModel::query()
            ->when(mb_strlen($code), function ($query) use ($code) {
                $query->where('code', $code);
            })
            ->when(mb_strlen($url), function ($query) use ($url) {
                $query->where('url', $url);
            })
            ->first();
        if ($shortUrlModel != null) {
            return [
                'code'     => $shortUrlModel->code,
                'url'      => $shortUrlModel->url,
                'shortUrl' => config('short-url.prefix') . $shortUrlModel->code,
            ];
        }

        if (!mb_strlen($url)) {
            return [
                'code'     => '',
                'url'      => '',
                'shortUrl' => ''
            ];
        }
        //生成短链
        $shortUrlModel = new ShortUrlMappingModel();
        $newCode       = Str::random(5);
        while (null != ShortUrlMappingModel::query()->where('code', $newCode)->first()) {
            $newCode = Str::random(5);
        }
        $shortUrlModel->code = $newCode;
        $shortUrlModel->url  = $url;
        $shortUrlModel->save();
        return [
            'code'     => $newCode,
            'url'      => $url,
            'shortUrl' => config('short-url.prefix') . $newCode,
        ];
    }


    public static function getShortUrl($code)
    {
        $model = ShortUrlMappingModel::query()->where('code', $code)->first();
        if (null === $model) {
            return null;
        }
        //数据库访问次数加一
        ShortUrlMappingModel::query()->where('code', $code)->update(['number' => DB::raw('number + 1')]);
        return [
            'url'  => $model->url,
            'code' => $model->code,
        ];
    }
}
